#%% init project env
import openai
import EsyPro

sfs = EsyPro.ScriptResultManager('zqf', locals(), version=0)

class OpenAIConversation:
    def __init__(self, api_key):
        """
        初始化 OpenAI 多轮对话类
        :param api_key: OpenAI API 密钥
        """
        self.api_key = api_key
        openai.api_key = self.api_key
        self.conversation_history = []

    def send_message(self, message):
        """
        向 OpenAI API 发送消息并获取回复
        :param message: 用户输入的消息
        :return: LLM 的回复
        """
        self.conversation_history.append({"role": "user", "content": message})
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=self.conversation_history
        )
        reply = response.choices[0]["message"]["content"].strip()
        self.conversation_history.append({"role": "assistant", "content": reply})
        return reply

    def reset_conversation(self):
        """
        重置对话历史
        """
        self.conversation_history = []

#%% main
if __name__ == '__main__':
    print(f'start {__file__}')
    
    # 测试代码
    api_key = "your_openai_api_key"
    conversation = OpenAIConversation(api_key)
    user_message = "请为以下任务生成Python代码：计算两个数的和"
    try:
        reply = conversation.send_message(user_message)
        print("LLM 回复：", reply)
    except openai.OpenAIError as e:
        print("OpenAI 错误：", e)
    except Exception as e:
        print("其他错误：", e)
    
    #%% end script
    print(f'end {__file__}')